package com.laborer.filter;

import com.sun.org.apache.xpath.internal.operations.Mod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
public class CustomFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        log.info(".............CustomFilter doFilter............");
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        HttpSession session = httpServletRequest.getSession();
        Object userId = session.getAttribute("userId");
        Object user = session.getAttribute("user");
        String requestURI = httpServletRequest.getRequestURI();
        if(requestURI.contains(".") || requestURI.contains("login") || requestURI.equals("/")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(userId==null){
            httpServletResponse.sendRedirect("/");
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

}
